package logic

import (
	"bytes"
	"context"
	"encoding/json"
	"io"
	"mime/multipart"
	"net/http"

	"goNutpi/internal/svc"
	"goNutpi/internal/types"

	"github.com/tidwall/gjson"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpc"
)

type PubArticleLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewPubArticleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PubArticleLogic {
	return &PubArticleLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *PubArticleLogic) PubArticle(req *types.PubArticleReq) (resp *types.PubArticleResp, err error) {
	// todo: add your logic here and delete this line
	url_ := "https://api.nutpi.net/user/control/topic/add"
	// 创建一个请求
	// 构建表单数据
	formData := &bytes.Buffer{}
	writer := multipart.NewWriter(formData)
	// 添加字段
	writer.WriteField("tagId", req.TagId)
	writer.WriteField("title", req.Title)
	writer.WriteField("isMarkdown", req.IsMarkdown)
	writer.WriteField("markdownContent", req.Content)
	writer.WriteField("captchaKey", "")
	// 关闭writer以确保所有数据都被正确写入到formData中
	err = writer.Close()
	if err != nil {
		l.Error("Error closing writer:", err)
		return nil, err
	}
	r, err := http.NewRequest("POST", url_, formData)
	if err != nil {
		l.Error(err)
		return nil, err
	}

	// 设置请求头
	r.Header.Set("authorization", req.Auth)
	r.Header.Set("x-requested-with", "XMLHttpRequest")
	r.Header.Set("Content-Type", writer.FormDataContentType())
	r.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3")
	//ctx := context.Background()
	//res, err_ := httpc.Do(ctx, http.MethodGet, url, nil)
	res, err_ := httpc.DoRequest(r)
	if err_ != nil {
		l.Error(err_)
		return nil, err
	}

	defer res.Body.Close()
	body, err := io.ReadAll(res.Body)
	if err != nil {
		l.Errorf("Failed to read response body:", err)
		return nil, err
	}

	var strResult bytes.Buffer
	_ = json.Indent(&strResult, []byte(body), "", "    ")
	l.Debugf("formated: ", strResult.String())

	if res.StatusCode >= 200 && res.StatusCode < 400 {
		result := gjson.GetBytes(body, "success").String()
		if result == "true" {
			resp = &types.PubArticleResp{
				Code:    0,
				Message: res.Status,
				Data:    "",
			}
		} else {
			resp = &types.PubArticleResp{
				Code:    1002,
				Message: strResult.String(),
				Data:    "",
			}
		}
	} else {
		resp = &types.PubArticleResp{
			Code:    res.StatusCode,
			Message: res.Status,
			Data:    "",
		}
	}

	return resp, nil

}
